import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Button, Popconfirm, message, Space } from 'antd';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PropTypes from 'prop-types';
import router from 'umi/router';
import styles from './style.less';
import RelateVehicleAdd from './relateVehicleAdd';
import TaskModal from './taskModal';

const mapStateToProps = (state: any) => ({
  dataPermission: state.menu.dataPermission,
  electricFenceMng: state.electricFenceMng,
  common: state.common,
  loading: state.loading.effects['electricFenceMng/getFetchPage'],
});
class RelateVehicle extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      formData: {},
      seriesOptions: [], // 车系
      typeOptions: [], //车型
      modalVisible: false,
      taskVisible: false,
      selectedRowKeys: [],
    };
  }
  fenceId: any;
  dealerCode: any;
  UNSAFE_componentWillMount() {
    this.fenceId = sessionStorage.getItem('fenceId');
    this.dealerCode = sessionStorage.getItem('dealerCode');
    // console.log(this.fenceId);
    this.handleGetVehicleSeriesList();
  }
  componentDidMount() {
    this.handleFlushPage();
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'electricFenceMng/initData',
    });
    sessionStorage.removeItem('fenceId');
    sessionStorage.removeItem('dealerCode');
  }

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      id: this.fenceId,
    };
    dispatch({
      type: 'electricFenceMng/postFetchPage',
      payload: { url: '/credit/vehicle/fence/queryAllCreditByFence', ...params },
    });
  };
  //查询车系
  handleGetVehicleSeriesList = () => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/msdevice/base/vehicle/series/list',
      },
      callback: response => {
        // if (response && response.statusCode == '0') {
        this.setState({
          seriesOptions: response.data || [],
        });
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };

  //根据车系code查询车型
  handleGetVehicleTypeList = seriesCode => {
    const {
      dataPermission: { BRAND = [] },
    } = this.props;
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/msdevice/base/vehicle/type/list',
        seriesCode,
        brandId: BRAND[0],
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          this.setState({
            typeOptions: response.data || [],
          });
        } else {
          this.setState({
            typeOptions: [],
          });
          message.error(response.statusMessage);
        }
      },
    });
  };

  // 新增关联车辆
  handleAdd = () => {
    this.setState({
      modalVisible: true,
    });
  };
  closeModal = refresh => {
    this.setState({
      modalVisible: false,
    });
    if (refresh) this.handleFlushPage();
  };
  // 解除关联
  handleDisassociate = data => {
    this.props.dispatch({
      type: 'http/postObj',
      payload: {
        url: `/credit/vehicle/fence/bathBind?id=${this.fenceId}&operatorType=1`,
        vinList: [data?.vin],
      },
      callback: response => {
        // if (response && response.statusCode == '0') {
        message.success('操作成功');
        this.handleFlushPage();
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };
  batchHandleDisassociate = () => {
    const { selectedRowKeys } = this.state;
    this.props.dispatch({
      type: 'http/postObj',
      payload: {
        url: `/credit/vehicle/fence/bathBind?id=${this.fenceId}&operatorType=1`,
        vinList: selectedRowKeys,
      },
      callback: response => {
        // if (response && response.statusCode == '0') {
        message.success('操作成功');
        this.handleFlushPage();
        this.setState({
          selectedRowKeys: [],
        });
        // } else {
        //   message.error(response.statusMessage);
        // }
      },
    });
  };
  back = () => {
    router.replace(`/electricFence/electricFenceMng`);
  };
  render() {
    const { formValues, seriesOptions, typeOptions, modalVisible, selectedRowKeys, taskVisible } =
      this.state;
    const {
      electricFenceMng: {
        pageData: { rows, pagination },
      },
      loading,
      // location: { pathname },
    } = this.props;
    const pathname = '/electricFence/electricFenceMng';
    const searchItems = [
      {
        type: 'input',
        title: 'VIN',
        key: 'vin',
      },
      {
        type: 'select',
        title: '车系',
        key: 'vehicleSeries',
        selectOptions: seriesOptions,
        keyValue: ['seriesCode', 'seriesName'],
        onChange: this.handleGetVehicleTypeList,
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: typeOptions,
        key: 'vehicleType',
        keyValue: ['typeCode', 'typeName'],
      },
    ];
    const columns = [
      { title: 'VIN', dataIndex: 'vin' },
      {
        title: '品牌',
        dataIndex: 'brandCodeName',
      },
      {
        title: '车系',
        dataIndex: 'vehicleSeriesName',
        // render: (text) => (
        //   <Ellipsis length={15} tooltip>
        //     {text}
        //   </Ellipsis>
        // ),
      },
      {
        title: '车型',
        dataIndex: 'vehicleTypeName',
        // render: (text) => (
        //   <Ellipsis length={15} tooltip>
        //     {text}
        //   </Ellipsis>
        // ),
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 218,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '解除关联',
              key: 'disassociate',
              auth: 'electricFenceMng_doDisassociate',
              Popconfirm: true,
              message: '是否确认解除关联？',
              onConfirm: () => this.handleDisassociate(record),
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: rows,
      loading,
      rowKey: (record: any) => record.vin,
      pagination: paginationProps,
      rowSelection: {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.setState({
            selectedRowKeys: selectedRowKeys,
          });
        },
      },
      scroll: { x: 'max-content' },
    };
    return (
      <div>
        <Card
          bordered={false}
          title="关联授信车辆"
          extra={
            <Space>
              <Button size="small" onClick={this.back}>
                返回
              </Button>
            </Space>
          }
        >
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'electricFenceMng/postFetchPage',
              url: '/credit/vehicle/fence/queryAllCreditByFence',
            }}
            extraArgs={{ id: this.fenceId }}
            saveFormValues={(val: any) => {
              return this.setState({ formValues: Object.assign(formValues, val) });
            }}
            handleFormReset={() => this.setState({ formValues: {}, typeOptions: [] })}
          />
        </Card>
        <Card className={styles.standardTable} bordered={false}>
          <div className="my_newItem">
            <Button size="small" type="primary" onClick={() => this.handleAdd()}>
              新增关联车辆
            </Button>
            <Button
              size="small"
              type="primary"
              onClick={() => this.setState({ taskVisible: true })}
            >
              任务中心
            </Button>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                key="batchDisassociate"
                title="确认批量解除关联车辆？"
                onConfirm={() => this.batchHandleDisassociate()}
              >
                <Button size="small" type="primary" danger onClick={e => e.stopPropagation()}>
                  批量解除关联
                </Button>
              </Popconfirm>
            )}

            {/* <Button size="small" type="primary">
              任务中心
            </Button>
            <Button size="small" type="danger">
              批量解除关联
            </Button> */}
          </div>

          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'electricFenceMng/postFetchPage',
              url: '/credit/vehicle/fence/queryAllCreditByFence',
              extraArgs: { id: this.fenceId },
            }}
            formValues={formValues}
          />
        </Card>
        {modalVisible && (
          <RelateVehicleAdd
            onRef={(val: any) => (this.relateVehicleModal = val)}
            modalVisible={modalVisible}
            seriesOptions={seriesOptions}
            closeModal={this.closeModal}
          />
        )}
        {taskVisible && (
          <TaskModal
            onRef={(val: any) => (this.taskModal = val)}
            changeTaskModalVisible={() => {
              this.setState({
                taskVisible: false,
              });
            }}
          />
        )}
      </div>
    );
  }
}
export default connect(mapStateToProps)(RelateVehicle);
